package com.kaibes.core.base.tag;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class TagMethod {

    private Map<String, Method> methodMap;
    
    public TagMethod() {
        this.methodMap = new HashMap<>();
    }
    
    public void addMethod(String tag, Method method) {
        methodMap.put(tag, method);
    }
    
    public void removeMethod(String tag) {
        methodMap.remove(tag);
    }
    
    public Object doMethod(Object target, String tag, Object...args) throws NoSuchMethodException {
        Method method = methodMap.get(tag);
        if (method == null) {
            throw new NoSuchMethodException("method("+tag+") not found!");
        }
        return invoke(method, target, args);
    }
    
    public void clear() {
        methodMap.clear();
    }

    private static Object invoke(Method method, Object receiver, Object... args) {
        try {
            method.setAccessible(true);
            Object o = method.invoke(receiver, args);
            return o;
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

}
